package web

import (
	"errors"
	"github.com/gin-gonic/gin"
	"log"
	"mts/trans_srv/internal/domain"
	"mts/trans_srv/internal/service"
	middleware "mts/trans_srv/internal/web/middleware"
	"net/http"
)

type TranslationHandler struct {
	transSvc   service.TranslationService
	lanSvc     service.LanService
	elementSvc service.ElementService
}

func NewTranslationHandler(transSvc service.TranslationService, lanSvc service.LanService) *TranslationHandler {
	return &TranslationHandler{
		transSvc: transSvc,
		lanSvc:   lanSvc,
	}
}

func (h *TranslationHandler) RegisterRoutes(group *gin.RouterGroup) {
	transGroup := group.Group("/trans")
	{
		transGroup.GET("/:id", h.GetTranslationsByLangId)
		transGroup.POST("/:eid/batch", middleware.JWTAuth(), middleware.IsAdminAuth(), h.BatchTranslation)
		transGroup.POST("/", middleware.JWTAuth(), middleware.IsAdminAuth(), h.InsertTranslation)
		transGroup.PUT("/", middleware.JWTAuth(), middleware.IsAdminAuth(), h.UpdateTranslation)
		transGroup.DELETE("/", middleware.JWTAuth(), middleware.IsAdminAuth(), h.DeleteTranslation)
	}
}

// BatchTranslation 批量添加翻译
func (h *TranslationHandler) BatchTranslation(ctx *gin.Context) {
	eid := ctx.Param("eid")
	//1. 校验组件是否存在
	elementInfo, err := h.elementSvc.FindElementByID(ctx, eid)
	if err != nil || &elementInfo == nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"msg": "无效的组件ID"})
		return
	}
	var translations []domain.Translation
	for _, v := range translations {
		v.ElementID = elementInfo.ID
	}
	//TODO 防止恶意添加语种,必须校验语种
	if err := ctx.ShouldBindJSON(&translations); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"msg": "参数错误"})
		return
	}
	if err := h.transSvc.BatchTranslation(ctx, translations); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"msg": "系统异常"})
		log.Printf("系统异常")
		return
	}
	ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "批量添加成功"})
}

// GetTranslationsByLangId 根据语种ID获取所有组件的信息
func (h *TranslationHandler) GetTranslationsByLangId(ctx *gin.Context) {
	id := ctx.Param("id")
	if len(id) == 0 {
		ctx.JSON(http.StatusBadRequest, gin.H{"msg": "无效的语种ID"})
		log.Println("Invalid language ID:", id)
		return
	}

	// 检查语种是否被启用
	lan, err := h.lanSvc.GetByLangID(ctx, id)
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"msg": "语种不存在"})
		log.Printf("Language not found for ID %s: %v", id, err)
		return
	}
	if !lan.Enabled {
		ctx.JSON(http.StatusForbidden, gin.H{"msg": "语种未启用"})
		log.Printf("Language %s is disabled", id)
		return
	}

	// 获取翻译信息
	translations, err := h.transSvc.GetTranslationsByLangId(ctx, id)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"msg": "系统异常"})
		log.Printf("Failed to get translations for language %s: %v", id, err)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "获取翻译信息成功", "data": translations})
}

func (h *TranslationHandler) InsertTranslation(ctx *gin.Context) {
	var translation domain.Translation
	if err := ctx.ShouldBindJSON(&translation); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"msg": "参数错误", "error": err.Error()})
		return
	}

	// 执行插入操作
	if err := h.transSvc.Insert(ctx, translation); err != nil {
		// 根据错误类型返回不同的响应
		if errors.Is(err, service.ErrConflict) {
			ctx.JSON(http.StatusConflict, gin.H{"msg": "资源冲突"})
			return
		} else {
			ctx.JSON(http.StatusInternalServerError, gin.H{"msg": "系统异常"})
			return
		}
	}

	ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "插入成功"})
}

func (h *TranslationHandler) UpdateTranslation(ctx *gin.Context) {
	var translation domain.Translation
	if err := ctx.ShouldBindJSON(&translation); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"msg": "参数错误", "error": err.Error()})
		return
	}

	// 执行更新操作
	if err := h.transSvc.Update(ctx, translation); err != nil {
		// 根据错误类型返回不同的响应
		if errors.Is(err, service.ErrRecordNotFound) {
			ctx.JSON(http.StatusNotFound, gin.H{"msg": "记录不存在"})
		} else if errors.Is(err, service.ErrConflict) {
			ctx.JSON(http.StatusConflict, gin.H{"msg": "资源冲突"})
		} else {
			ctx.JSON(http.StatusInternalServerError, gin.H{"msg": "系统异常"})
		}
		log.Printf("Update operation failed: %v", err)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "更新成功"})
}

func (h *TranslationHandler) DeleteTranslation(ctx *gin.Context) {
	var translation domain.Translation
	if err := ctx.ShouldBindJSON(&translation); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"msg": "参数错误", "error": err.Error()})
		log.Println("Invalid request body:", err)
		return
	}
	// 执行删除操作
	if err := h.transSvc.Delete(ctx, translation); err != nil {
		// 根据错误类型返回不同的响应
		if errors.Is(err, service.ErrRecordNotFound) {
			ctx.JSON(http.StatusNotFound, gin.H{"msg": "记录不存在"})
			return
		} else {
			ctx.JSON(http.StatusInternalServerError, gin.H{"msg": "系统异常"})
			return
		}
	}
	ctx.JSON(http.StatusOK, gin.H{"code": 200, "msg": "删除成功"})
}
